<?php

declare(strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use app\common\tool\excel\Export;
use think\Response;
use app\common\tool\Result;
use think\facade\View;
use think\response\Json;
use app\common\model\Cate;
use app\common\model\Paper;
use app\common\model\PaperBank;
//该文件为自动生成，请按需修改
class Exam extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    protected string $validate = 'Exam';
    //主模型
    protected string $model = '\app\common\model\Exam';

    protected $append = ['cateText', 'typesText'];
    public function index(): string
    {
        $param = $this->request->param();
        if (isset($param['addExam']) && $param['addExam'] == 1) {
            return Builder::Table()
                ->autoStructure($this->model, $this->pk, '')
                ->addSearch([
                    ['title', '题目', 'input,Like'],
                ],false)
                ->fetch('exam/index');
        } else {
            return Builder::Table()
                ->autoStructure($this->model, $this->pk, 'barDemo,200')->addTopButtons([
                    'add' => ['size' => '60%'],
                    'download' => [
                        'title' => '下载模板',
                        'icon' => 'layui-icon-download-circle',
                        'class' => 'normal export-boost',
                        'url' => '/muban/题库信息.xlsx',
                        'event' => '_download'
                    ],
                    'import' => [
                        'title' => '导入题库',
                        'icon' => 'layui-icon-upload-drag',
                        'class' => 'normal import-boost Import',
                        'exts' => 'xls|xlsx',
                        'type' => 'Import',
                        'url' => url('exam/importInfo')->build(),
                        'event' => '_import',
                        'init' => true
                    ],
                    'deleteAll'
                ])
                ->addRightButtons(
                    [
                        'edit'  => ['size' => '50%'],
                        'delete'
                    ]
                )
                ->addSearch([
                    ['title', '题目', 'input,Like'],
                ])
                ->fetch();
        }
    }
    public function add($tpl = 'exam/edit')
    {
        $cate = Cate::where('pid', 0)->order('sort asc')->select();
        $answer = self::getAnswer();
        view::assign(
            [
                'cate' => $cate,
                'radio_answer' => $answer,
                'checkbox_answer' => $answer,
            ]
        );
        return parent::add($tpl); // TODO: Change the autogenerated stub
    }

    public function edit($id = '', $tpl = 'exam/edit', $info = '')
    {
        $cate = Cate::where('pid', 0)->order('sort asc')->select();
        $answer = self::getAnswer();
        $info = $this->model::find($id);
        foreach ($answer as $k => $v) {
            if ($info['types'] == 2) {
                $answerlist = explode(',', $info['answer']);
                if (in_array($v['title'], $answerlist)) {
                    $v['check'] = 1;
                } else {
                    $v['check'] = 0;
                }
            } else {
                $v['check'] = $info['answer'] == $v['title'] ? 1 : 0;
            }
            $answer[$k] = $v;
        }
        // print('<pre>');print_r($answer);die;
        view::assign(
            [
                'cate' => $cate,
                'radio_answer' => $answer,
                'checkbox_answer' => $answer,
            ]
        );
        return parent::edit($id, $tpl, $info); // TODO: Change the autogenerated stub
    }
    public static function getAnswer()
    {
        $answer = [
            [
                'title' => 'A',
                'check' => 0,
            ],
            [
                'title' => 'B',
                'check' => 0,
            ],
            [
                'title' => 'C',
                'check' => 0,
            ],
            [
                'title' => 'D',
                'check' => 0,
            ],
            [
                'title' => 'E',
                'check' => 0,
            ]
        ];
        return $answer;
    }

    public function save($param = [], $model = false): Json
    {
        $param = $this->request->post();
        if ($param['types'] == 1) {
            $param['answer'] = $param['radio_answer'];
            if (empty($param[$param['answer']])) {
                return Result::fail('正确答案数据不能为空');
            }
        } else {
            $param['answer'] = $param['checkbox_answer'];
            $answer = explode(',', $param['answer']);
            foreach ($answer as $k => $v) {
                if (empty($param[$v])) {
                    return Result::fail('正确答案数据不能为空');
                }
            }
        }
        unset($param['checkbox_answer']);
        unset($param['radio_answer']);
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }
    /**
     * 导入
     */
    public function importInfo()
    {
        try {
            $file = request()->file('file');
            $file_info = pathinfo($file->getOriginalName());
            $name = filegenerate(32) . '.' . $file_info['extension'];
            $fileurl = 'uploads/file/' . date('Ymd') . '/';
            $url = '/uploads/file/' . date('Ymd') . '/';
            $local = app()->getRootPath() . 'public/uploads/file/' . date('Ymd') . '/';
            $file->move($local, $name);
            if (!file_exists($fileurl . $name)) {
                return Result::fail('导入文件不存在！');
            }
            $list = Export::excelImport('.' . $url . $name, ucfirst($file_info['extension']));
            // print('<pre>');print_r($list);die;
            if ($list['code'] == 1) {
                foreach ($list['data'] as $key => $value) {
                    $info = $this->model::where(['title' => $value[0], 'cate' => $value[1]])->find();
                    $data = [
                        'title' => $value[0],
                        'cate' => $value[1],
                        'images' => !empty($value[2]) ? implode(',', $value[2]) : '',
                        'A' => $value[3],
                        'B' => $value[4],
                        'C' => $value[5],
                        'D' => $value[6],
                        'E' => $value[7],
                        'answer' => $value[8],
                        'parse' => $value[9],
                        'types' => $value[10] == "单选" ? 1 : 2,
                    ];
                    if (!empty($info)) {
                        $this->model::where('id', $info['id'])->update($data);
                    } else {
                        $this->model::create($data);
                    }
                }
                if (file_exists($fileurl . $name)) {
                    unlink('./' . $fileurl . $name);
                }
                return Result::success('导入数据成功！');
            } else {
                return Result::fail($list['msg']);
            }
        } catch (\Exception $e) {
            return Result::fail('上传失败：' . $e->getMessage());
        }
    }

    public function getExamList(): Response
    {
        try {
            $param = request()->get();
            $cate = Paper::where('id',$param['paper_id'])->value('cate');
            if(isset($param['title']) && $param['title']){
                $map[] = ['title', 'like', '%' . $param['title'] . '%'];
            }
            $map[] = ['types', '=', $param['types']];
            $map[] = ['cate', '=', $cate];
            $paper_id =PaperBank::where([['types', '=', $param['types']],['cate', '=', $cate],['paper_id','=',$param['paper_id']]])->column('exam_id');
            $list = $this->model::where($map)->append(['typesText','cateText'])->page(intval($param['page']), intval($param['limit']))->order('create_time desc')->select();
            foreach ($list as &$v) {
               $v->check = in_array($v['id'],$paper_id)?1:0;
            }
            $count = $this->model::where($map)->count();
            return Result::fastReturn(['code' => 0, 'count' => $count, 'data' => $list]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
